package com.itheima.book.dao;
//完成数据增删操作，供Service层调用

import com.itheima.book.domain.Book;

import java.util.ArrayList;

public class Book2Dao implements BookBaseDao {
    //定义一个成员变量，ArrayList，用来存储Book数据。
    private static ArrayList<Book> arrayListBooks = new ArrayList<>();

    //添加
    public boolean addBook(Book book) {
        arrayListBooks.add(book);

        return true;

    }


    public Book[] allBooks() {
        Book[] books = new Book[arrayListBooks.size()];
        for (int i = 0; i < arrayListBooks.size(); i++) {
            Book book = arrayListBooks.get(i);
            books[i] = book;
        }
        return books;
    }

    //删除

    public void deleteByBookId(String bookId) {
        int index = -1;
        for (int i = 0; i < arrayListBooks.size(); i++) {
            Book book = arrayListBooks.get(i);
            if (book != null) {

                if (book.getBookId().equals(bookId)) {
                    index = i;
                    break;
                }
            }
        }
        if (index != -1) {
            arrayListBooks.remove(index);
        }

    }

    //修改
    public void updateBookByBookId(Book book) {
        int index = -1;
        for (int i = 0; i < arrayListBooks.size(); i++) {
            if (arrayListBooks.get(i) != null) {
                if (arrayListBooks.get(i).getBookId() == book.getBookId()) {
                    index = i;

                }
            }
        }
        if (index != -1) {
            arrayListBooks.set(index, book);
        }
    }
}
